package com.b2c.erp.controller.order.erp;

import com.b2c.entity.result.PagingResponse;
import com.b2c.common.utils.DateUtil;
import com.b2c.entity.erp.ErpSalesOrderEntity;
import com.b2c.entity.erp.ErpSalesOrderItemEntity;
import com.b2c.entity.enums.erp.EnumErpOrderStatus;
import com.b2c.entity.enums.erp.EnumSalesOrderPayStatus;
import com.b2c.erp.DataConfigObject;
import com.b2c.entity.ErpContactEntity;
import com.b2c.repository.utils.OrderNumberUtils;
import com.b2c.interfaces.wms.ClientManageService;
import com.b2c.interfaces.erp.ErpGoodsService;
import com.b2c.interfaces.erp.ErpSalesOrderService;
import com.b2c.entity.vo.erp.ErpSalesOrderDetailVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping(value = "/erp_sales")
public class ErpOrderController {
    @Autowired
    private ErpSalesOrderService erpSalesOrderService;
    @Autowired
    private ErpGoodsService erpGoodsService;
    @Autowired
    private ClientManageService clientManageService;

    /**
     * ERP系统下单
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "/order_create", method = RequestMethod.GET)
    public String login(Model model, HttpServletRequest request) {

        //查询客户列表
//        List<UserEntity> clientList = userService.getClientUserListByType(null, null);
//        model.addAttribute("clientList", clientList);

        PagingResponse<ErpContactEntity> clientList = clientManageService.getClientList(1, 100, null, null,-10,99);//-10代表是客户
        model.addAttribute("clientList", clientList.getList());

        model.addAttribute("menuId", "order_create");
        

        model.addAttribute("view", "ddcx-erp");
        model.addAttribute("pView", "sale");
        return "shopOrder/erp_sales_order_create";

    }

    /**
     * ERP系统下单POST
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "/order_create", method = RequestMethod.POST)
    public String postSystemOrder(Model model, HttpServletRequest request) {
        HttpSession session = request.getSession();
        Object userId = request.getSession().getAttribute("userId");
        //return "/permission_denied";
        model.addAttribute("menuId", "system_order");
        /***商品信息****/
        String[] specNumber = request.getParameterValues("specNumber");//规格编码组合
        String[] goodsNumber = request.getParameterValues("goodsNumber");//商品编码组合
        String[] goodsId = request.getParameterValues("goodsId");//商品id组合
        String[] specsId = request.getParameterValues("specId");//商品规格id组合
        String[] quantitys = request.getParameterValues("quantity");//数量组合
        String[] prices = request.getParameterValues("note");//商品价格
        //收件人信息
        String contactMobile = request.getParameter("contactMobile");
        String contactPerson = request.getParameter("contactPerson");
        String area = request.getParameter("area");
        String address = request.getParameter("address");
        String saleType = request.getParameter("saleType");
        String shippingFee= StringUtils.isEmpty(request.getParameter("shippingFee")) ? "0" :request.getParameter("shippingFee");
        String sellerMemo = request.getParameter("sellerMemo");
        Integer payStatus = Integer.parseInt(request.getParameter("payStatus"));
        Integer payMethod = 0;
        if(StringUtils.isEmpty(request.getParameter("payMethod"))==false){
            payMethod = Integer.parseInt(request.getParameter("payMethod"));
        }

        String[] areaNameArray = area.split(" ");

        String provinceName = "";
        if (areaNameArray.length > 0) provinceName = areaNameArray[0];
        String cityName = "";
        if (areaNameArray.length > 1) cityName = areaNameArray[1];
        String districtName = "";
        if (areaNameArray.length > 2) districtName = areaNameArray[2];

        //下单人信息
        String buyerUserId = request.getParameter("buyerUserId");
        ErpSalesOrderDetailVo salesOrder= new ErpSalesOrderDetailVo();
        List<ErpSalesOrderItemEntity> items=new ArrayList<>();
        Long goodsCount=0L;//商品数量
        Long goodsSpecCount=0L;//商品规格数量
        double goodsTotalAmount = 0;//商品总价
        for (int i = 0,n=goodsId.length;i<n;i++) {
            if(StringUtils.isEmpty(goodsId[i]))continue;
            ErpSalesOrderItemEntity item= new ErpSalesOrderItemEntity();
            Integer specId=Integer.parseInt(specsId[i]);
            BigDecimal price = new BigDecimal(prices[i]);
            Integer count =Integer.parseInt(quantitys[i]);
            var spec = erpGoodsService.getSpecBySpecId(specId);
            //if(count.intValue()>spec.getCurrentQty())continue;
            goodsCount+=count;
            goodsSpecCount++;
            goodsTotalAmount +=  price.doubleValue() * count;
            item.setGoodsId(Integer.parseInt(goodsId[i]));
            item.setSpecId(specId);
            item.setSpecNumber(specNumber[i]);
            item.setGoodsNumber(goodsNumber[i]);
            item.setQuantity(count);
            item.setPrice(price);
            item.setDiscountPrice(price);
            item.setGoodsTitle(spec.getGoodTitle());
            item.setGoodsImage(spec.getColorImage());
            item.setColor(spec.getColorValue());
            item.setSize(spec.getSizeValue());
            item.setSkuInfo(item.getColor()+" "+item.getSize());
            items.add(item);
        }
//        UserEntity client=null;
//        if(StringUtils.isEmpty(buyerUserId)==false) {
//            client = userService.getUserById(Integer.parseInt(buyerUserId));//用户信息
//        }
        salesOrder.setGoodsCount(goodsCount);
        salesOrder.setGoodsSpecCount(goodsSpecCount);
        salesOrder.setGoodsTotalAmount(new BigDecimal(goodsTotalAmount));
        salesOrder.setContactMobile(contactMobile);
        salesOrder.setContactPerson(contactPerson);
        salesOrder.setProvince(provinceName);
        salesOrder.setCity(cityName);
        salesOrder.setArea(districtName);
        salesOrder.setAddress(provinceName+cityName+districtName+address);
        salesOrder.setItems(items);
        salesOrder.setSaleType(Integer.parseInt(saleType));
        salesOrder.setShippingFee(new BigDecimal(0));
        salesOrder.setBuyerUserId(Integer.parseInt(buyerUserId));
        salesOrder.setBuyerName(contactPerson);
//        if(client != null) {
//            salesOrder.setDeveloperId(client.getDeveloperId());
//            salesOrder.setBuyerUserId(Integer.parseInt(buyerUserId));
//            salesOrder.setBuyerName(client.getUserName());
//        }else {
//            salesOrder.setDeveloperId(0);
//            salesOrder.setBuyerUserId(0);
//            salesOrder.setBuyerName(contactPerson);
//        }

        salesOrder.setShopId(99);

        salesOrder.setOrderNum(OrderNumberUtils.getOrderIdByTime());
        salesOrder.setTotalAmount(new BigDecimal(goodsTotalAmount).add(new BigDecimal(shippingFee)));
        salesOrder.setOrderTime(System.currentTimeMillis() / 1000);

        if(payStatus.intValue() == 0){
            //未付款订单
            salesOrder.setStatus(EnumErpOrderStatus.WaitSend.getIndex());
            salesOrder.setPayAmount(new BigDecimal(0));//付款金额
            salesOrder.setPayTime(0L);
            salesOrder.setPayStatus(EnumSalesOrderPayStatus.NotPay.getIndex());
        }else if(payStatus.intValue() == 2){
            //已付款订单
            salesOrder.setStatus(EnumErpOrderStatus.WaitSend.getIndex());
            salesOrder.setPayAmount(new BigDecimal(goodsTotalAmount).add(new BigDecimal(shippingFee)));//付款金额
            salesOrder.setPayTime(System.currentTimeMillis() / 1000 );
            salesOrder.setPayStatus(EnumSalesOrderPayStatus.CompletePay.getIndex());
        }

        salesOrder.setPayMethod(payMethod);


        salesOrder.setOrderDate(DateUtil.getCurrentDate());
        salesOrder.setShippingFee(new BigDecimal(shippingFee));
        salesOrder.setSellerMemo(sellerMemo);
        salesOrder.setCreateOn(System.currentTimeMillis() / 1000);
        salesOrder.setAuditStatus(0);

        if(goodsCount>0)erpSalesOrderService.editSalesOrder(salesOrder);
        return "redirect:/erp_sales/order_list";
    }

    /**
     * 订单列表
     *
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "/order_list", method = RequestMethod.GET)
    public String orderList(Model model,  HttpServletRequest request) {
        model.addAttribute("menuId", "order_list");


        String page = request.getParameter("page");
        Integer pageIndex = 1;
        Integer pageSize = DataConfigObject.getInstance().getPageSize();
        String orderNum = "";
        String contactMobile = "";
        Integer startTime = 0;
        Integer endTime = 0;
        Integer saleType = null;
        Integer shopId = null;
        Integer buyerUserId = null;
        Integer status = null;
        Integer auditStatus = null;


        if (!StringUtils.isEmpty(page)) {
            pageIndex = Integer.parseInt(page);
        }
        if (!StringUtils.isEmpty(request.getParameter("pageSize"))) {
            try {
                pageSize = Integer.parseInt(request.getParameter("pageSize"));
            } catch (Exception e) {
            }
        }
        if (!StringUtils.isEmpty(request.getParameter("orderNum"))) {
            orderNum = request.getParameter("orderNum");
        }
        if (!StringUtils.isEmpty(request.getParameter("contactMobile"))) {
            contactMobile = request.getParameter("contactMobile");
        }


        if (!StringUtils.isEmpty(request.getParameter("buyerUserId"))) {
            buyerUserId = Integer.parseInt(request.getParameter("buyerUserId"));
            model.addAttribute("buyerUserId", buyerUserId);
        }
        if (!StringUtils.isEmpty(request.getParameter("status"))) {
            status = Integer.parseInt(request.getParameter("status"));
            model.addAttribute("status",status);
        }
        if (!StringUtils.isEmpty(request.getParameter("auditStatus"))) {
            auditStatus = Integer.parseInt(request.getParameter("auditStatus"));
            model.addAttribute("auditStatus",auditStatus);
        }
        if (!StringUtils.isEmpty(request.getParameter("type"))) {
            saleType = Integer.parseInt(request.getParameter("type"));
            model.addAttribute("saleType",saleType);
        }
        if (!StringUtils.isEmpty(request.getParameter("shopId"))) {
            shopId = Integer.parseInt(request.getParameter("shopId"));
            model.addAttribute("shopId",shopId);
        }

        if (!StringUtils.isEmpty(request.getParameter("startTime"))) {
            startTime = DateUtil.dateToStamp(request.getParameter("startTime"));
        }
        if (!StringUtils.isEmpty(request.getParameter("endTime"))) {
            endTime = DateUtil.dateTimeToStamp(request.getParameter("endTime") + " 23:59:59");
        }


        model.addAttribute("pageIndex", pageIndex);
        model.addAttribute("pageSize", pageSize);
        PagingResponse<ErpSalesOrderEntity> result = erpSalesOrderService.getList(pageIndex, pageSize, orderNum, contactMobile, saleType, buyerUserId, status,shopId,auditStatus, startTime, endTime);
        model.addAttribute("totalSize", result.getTotalSize());
        model.addAttribute("lists", result.getList());

        //查询业务员
//        List<UserEntity> developerList = userService.getDeveloperList();
//        model.addAttribute("developerList", developerList);

        //店铺列表
//        List<DcShopEntity> shops = shopService.getShopList(null);
//        model.addAttribute("shops", shops);

        //查询客户列表
        PagingResponse<ErpContactEntity> clientList = clientManageService.getClientList(1, 100, null, null,-10,99);//-10代表是客户
        model.addAttribute("clientList", clientList.getList());

        model.addAttribute("view", "ddcx-erp");
        model.addAttribute("pView", "sale");
        return "shopOrder/erp_sales_order_list";
    }

    /**
     * 订单详情
     *
     * @param model
     * @param id      订单Id
     * @param request
     * @return
     */
    @RequestMapping(value = "/order_detail", method = RequestMethod.GET)
    public String getOrderDetail(Model model, @RequestParam Long id, HttpServletRequest request) {
        var orderDetail = erpSalesOrderService.getDetailById(id);
        model.addAttribute("order", orderDetail);
        model.addAttribute("shopId", orderDetail.getShopId());
        model.addAttribute("menuId", "order_list");
        model.addAttribute("view", "ddcx-erp");
        model.addAttribute("pView", "sale");
        return "shopOrder/erp_sales_order_detail";
    }

    /**
     * 订单确认弹窗
     *
     * @param model
     * @param orderId
     * @param request
     * @return
     */
    @RequestMapping(value = "/order_confirm", method = RequestMethod.GET)
    public String orderConfirmGet(Model model, @RequestParam Long orderId, HttpServletRequest request) {
        var order = erpSalesOrderService.getDetailById(orderId);
        if (order == null) {
            model.addAttribute("error", "没有找到订单");
            model.addAttribute("orderVo", new ErpSalesOrderDetailVo());

        } else {
            model.addAttribute("orderVo", order);
        }

        return "shopOrder/erp_sales_order_confirm";
    }
}
